/** @format */

export default {
    exportExcel: function (trStr, columns, jsonData, fileName, id) {
        // debugger;

        //循环遍历，每行加入tr标签，每个单元格加td标签
        for (let i = 0; i < jsonData.length; i++) {
            trStr += `<tr>`;

            for (let j = 0; j < columns.length; j++) {
                let column = columns[j];

                let value = jsonData[i][column];

                if (!value) {
                    if (value === 0) {
                        value = 0;
                    } else {
                        value = '';
                    }
                }

                if (column == 'JCSJ') {
                    //在td元素上加一个样式（时间格式可以自己设置例如：yyyy-mm-dd）
                    trStr += `<td align="center" style="vnd.ms-excel.numberformat:yyyy-mm">${value}</td>`;
                } else {
                    const bgColor = i % 2 == 0 ? '#fff' : '#f5f5f5';
                    //增加\t为了不让表格显示科学计数法或者其他格式
                    trStr += `<td  style="height:50px;border:1px solid #EBEEF5;background-color:${bgColor}" align="center">${
                        value + '\t'
                    }</td>`;
                }
            }
            trStr += '</tr>';
        }

        //Worksheet名
        let uri = 'data:application/vnd.ms-excel;base64,';

        //下载的表格模板数据
        let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40">
      <head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${trStr}</table></body></html>`;

        //下载模板
        function base64(s) {
            return window.btoa(unescape(encodeURIComponent(s)));
        }

        document.getElementById(id).href = uri + base64(template);
        document.getElementById(id).download = fileName;
        document.getElementById(id).click();
    }
};
